package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备功能Service业务层处理
 * 
 * @author mr.chen
 * @date 2025-05-25
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备功能
     * 
     * @param id 设备功能主键
     * @return 设备功能
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备功能列表
     * 
     * @param device 设备功能
     * @return 设备功能
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备功能
     * 
     * @param device 设备功能
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备功能
     * 
     * @param dto 设备功能
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto dto)
    {
        //获取备注名称
        String nickname = dto.getRegisterDeviceRequest().getNickname();
        //根据id查询设备信息
        Device deviceOne = this.lambdaQuery()
                .eq(Device::getId, dto.getId())
                .one();
        //修改华为云IOT接口内容
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceOne.getIotId());
        UpdateDevice body = new UpdateDevice();
        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        body.withAuthInfo(authInfobody);
        body.withDescription(nickname);
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if(response == null || response.getHttpStatusCode() != 200){
            throw new BaseException("修改设备失败");
        }

        //查询同一位置是否绑定同样的产品
        Long count = this.lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .ne(Device::getId,dto.getId())
                .count();
        if (count > 0) {
            throw new BaseException("该位置已经绑定过此产品");
        }
        Device device = new Device();
        BeanUtils.copyProperties(dto,device);
        if(dto.getLocationType() == 0){
            this.lambdaUpdate()
                    .eq(Device::getId,device.getId())
                    .set(Device::getPhysicalLocationType,null)
                    .update();
        }
        device.setNickname(nickname);
        return updateById(device) ? 1 : 0;
    }

    /**
     * 删除设备功能信息
     * 
     * @param dto 设备功能主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(DeviceDto dto)
    {
        //获取设备id
        String iotId = dto.getIotId();
        //删除阿里云设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        //删除数据库
        boolean remove = this.lambdaUpdate()
                .eq(Device::getIotId, iotId)
                .remove();
        return remove ? 1 : 0;
    }

    @Autowired
    private IoTDAClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //同步数据
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if(response.getHttpStatusCode() != 200 || response == null){
            throw new BaseException("同步数据失败");
        }
        //把数据存储到redis中
        redisTemplate.opsForValue().set(CacheConstants.HUAWEU_IOTDA_LIST, JSON.toJSONString(response.getProducts()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中读取数据
        String productListJSON = redisTemplate.opsForValue().get(CacheConstants.HUAWEU_IOTDA_LIST);
        if(StringUtils.isBlank(productListJSON)){
            throw new BaseException("获取数据失败");
        }
        List<ProductSummary> productSummaries = JSON.parseArray(productListJSON, ProductSummary.class);
        List<ProductVo> productVoList = productSummaries.stream().map(x -> {
            return ProductVo.builder().productKey(x.getProductId()).productName(x.getName()).build();
        }).collect(Collectors.toList());
        return productVoList;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(DeviceDto dto) {
        //查询设备名称是否重复
        Long deviceNameCount = this.lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName())
                .count();
        if(deviceNameCount >0){
            throw new BaseException("已经有该设备名称");
        }
        String nodeId = IdUtil.getSnowflakeNextIdStr();//雪花算法
        //查询设备id是否重复
        Long iotIdCount = this.lambdaQuery()
                .eq(Device::getIotId, dto.getIotId())
                .count();
        if(iotIdCount >0){
            throw new BaseException("已经有该设备id");
        }
        //查询同一位置是否绑定同样的产品
        Long count = this.lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .count();
        if(count >0){
            throw new BaseException("该位置已经绑定过此产品");
        }
        //创建设备
        AddDeviceRequest request = new AddDeviceRequest();

        AuthInfo authInfo = new AuthInfo();
        String secret = IdUtil.fastSimpleUUID();//生成uuid
        authInfo.setSecret(secret);//设备密钥

        AddDevice body = new AddDevice();
        body.setNodeId(nodeId);//设备标识码
        body.setProductId(dto.getProductKey());//产品id
        String description = dto.getRegisterDeviceRequest().getNickname();//设备描述
        body.setDescription(description);//设备描述
        body.setDeviceName(dto.getDeviceName());//设备名称
        body.setAuthInfo(authInfo);

        request.withBody(body);

        AddDeviceResponse response = client.addDevice(request);
        if(response == null || response.getHttpStatusCode() != 201){
            throw new BaseException("注册设备失败");
        }
        //解析数据获取结果
        String iotId = response.getDeviceId();

        //添加数据
        Device device = new Device();
        BeanUtils.copyProperties(dto,device);
        device.setIotId(iotId);//设备id
        device.setNodeId(nodeId);//设备标识码
        device.setSecret(secret);//设备秘钥
        device.setNickname(description);//备注名称
        device.setDeviceDescription(description);//设备描述
        device.setProductKey(dto.getProductKey());//产品id
        device.setProductName(getProductName(dto.getProductKey()));//产品名称
        boolean save = this.save(device);
        if(!save){
            throw new BaseException("注册设备失败");
        }
    }

    /**
     * 根据产品id查询产品名称
     * @param productKey
     * @return
     */
    private String getProductName(String productKey) {
        String productListJSON = redisTemplate.opsForValue().get(CacheConstants.HUAWEU_IOTDA_LIST);
        if(StringUtils.isBlank(productListJSON)){
            throw new BaseException("获取产品失败");
        }
        List<ProductSummary> productSummaries = JSONUtil.toList(productListJSON, ProductSummary.class);
        if(CollectionUtils.isNotEmpty(productSummaries)){
            ProductSummary productSummary = productSummaries.stream().filter(p -> p.getProductId().equals(productKey)).findFirst().get();
            if(productSummary != null){
                return productSummary.getName();
            }
        }
        return null;
    }

    @Autowired
    private ISysUserService userService;
    @Autowired
    private HuaWeiIotConfigProperties properties;

    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询该设备信息
        Device device = this.lambdaQuery()
                .eq(Device::getIotId, iotId)
                .one();
        if(device == null){
            throw new BaseException("该设备未被注册");
        }
        //拷贝数据
        DeviceDetailVo deviceDetailVo = new DeviceDetailVo();
        BeanUtils.copyProperties(device,deviceDetailVo);
        //补充数据
        deviceDetailVo.setDeviceSecret(device.getSecret());//设备秘钥
        deviceDetailVo.setRegion(properties.getRegionId());//时区
        SysUser sysUser = userService.selectUserById(Long.valueOf(device.getCreateBy()));//查询用户
        deviceDetailVo.setCreator(sysUser.getUserName());//创建人

        //调用华为IOT接口查询设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if(response == null || response.getHttpStatusCode() != 200){
            throw new BaseException("调用华为IOT接口查询设备详情失败");
        }
        //补充数据
        deviceDetailVo.setStatus(response.getStatus());//设备状态，ONLINE：设备在线，OFFLINE：设备离线，ABNORMAL：设备异常，INACTIVE：设备未激活，FROZEN：设备冻结
        deviceDetailVo.setDeviceStatus(response.getStatus());
        deviceDetailVo.setFirmwareVersion(response.getFwVersion());//固件版本
        String activeTime = response.getActiveTime();//设备激活时间。格式：yyyy-MM-dd'T'HH:mm:ss.SSS'Z' ，如2015-12-12T12:12:122Z。国际时间,比东八区早八小时
        if(StringUtils.isNotBlank(activeTime)){
            LocalDateTime gmtActive = OffsetDateTime.parse(activeTime).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            deviceDetailVo.setGmtActive(gmtActive);//激活时间
        }
        deviceDetailVo.setGmtCreate(device.getCreateTime());//创建时间

        return deviceDetailVo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //参数校验
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云IOT查询产品详情
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if(response == null || response.getHttpStatusCode() != 200){
            throw new BaseException("调用华为云IOT查询产品详情失败");
        }
        //获取数据
        List<ServiceCapability> capabilityList = response.getServiceCapabilities();
        if(CollUtil.isEmpty(capabilityList)){
            throw new BaseException("获取产品详情失败");
        }
        ServiceCapability serviceCapability = capabilityList.get(0);
        //转成小驼峰命名
        JSONObject entries = JSONUtil.parseObj(serviceCapability);
        return entries;
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param deviceName
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName) {
        //1. 判断设备是否存在
        Device device = this.lambdaQuery().eq(Device::getDeviceName, deviceName).select(Device::getIotId).one();
        if(device==null) {
            throw new BaseException("设备不存在");
        }
        String deviceId = device.getIotId();//获取设备id

        //2. 调用华为云IOT接口查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(deviceId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if(response==null || response.getHttpStatusCode()!=200) {
            throw new BaseException("调用华为云IOT接口查询设备影子数据失败");
        }

        //3. 解析响应结果数据，封装map的数据
        List<DeviceShadowData> shadowDataList = response.getShadow();
        if(CollUtil.isEmpty(shadowDataList)) {
            throw new BaseException("调用华为云IOT接口查询设备影子数据为空");
        }
        DeviceShadowData shadowData = shadowDataList.get(0);
        DeviceShadowProperties reported = shadowData.getReported();
        //事件操作时间，格式：yyyyMMdd'T'HHmmss'Z'，如20151212T121212Z。该值是国际标准时间，比东八区早八小时
        String eventTimeStr = reported.getEventTime();//数据上报时间
        //转为东八区时间
        LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        JSONObject properties = JSONUtil.parseObj(reported.getProperties());
        List<Map<String,Object>> propertyStatusInfo = new ArrayList<>();
        properties.forEach((k,v)->{
            //封装属性对象
            Map<String,Object> propertyMap = new HashMap<>();
            propertyMap.put("identifier",k);
            propertyMap.put("name",k);
            propertyMap.put("value",v);
            propertyMap.put("time",eventTime);
            propertyStatusInfo.add(propertyMap);
        });

        //4. 返回Map数据
        Map<String,Object> resultMap = new HashMap<>();

        Map<String,Object> propertyStatusInfoMap = new HashMap<>();
        propertyStatusInfoMap.put("propertyStatusInfo", propertyStatusInfo);

        resultMap.put("list",propertyStatusInfoMap);

        return resultMap;
    }
}
